package org.ghl.gulimalltest.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.ghl.common.utils.PageUtils;
import org.ghl.common.utils.Query;

import org.ghl.gulimalltest.product.dao.CategoryDao;
import org.ghl.gulimalltest.product.entity.CategoryEntity;
import org.ghl.gulimalltest.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出所有商品分类，组装成树形结构集合返回
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有分类
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);

        //组装成树形结构

        //找到所有产品的一级分类并排序
        List<CategoryEntity> level1Menus = categoryEntityList.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildrens(menu, categoryEntityList));
                    return menu;
                }).sorted((menu1, menu2) -> {
                    return (menu1.getSort()==null?0:menu1.getSort()) -( menu2.getSort()==null?0:menu2.getSort());
                }).collect(Collectors.toList());


        return level1Menus;
    }

    /**
     * 在指定菜单没有被引用的情况下，删除指定菜单且
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 判断菜单有没有被引用


        //批量删除(逻辑删除)
        baseMapper.deleteBatchIds(asList);


    }

    //使用递归方法获取当前分类的子分类
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> chidren = all.stream().filter((allCategoryEntity) -> {
            return allCategoryEntity.getParentCid() == root.getCatId();//获取root分类的子分类，也是这个递归的出口

        }).map(categoryEntity -> {
            //此处递归核心，找出子分类
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //菜单排序
            return (menu1.getSort()==null?0:menu1.getSort()) -( menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return chidren;
    }


}